package com.hangzhou.xyj;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDexApplication;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.hangzhou.xyj.db.SimpleUserDao;
import com.hangzhou.xyj.db.UserDao;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.engine.BaiduMapLocationEngine;
import com.hangzhou.xyj.event.LocationRespEvent;
import com.hangzhou.xyj.event.base.EventCode;
import com.hangzhou.xyj.manager.ChatManager;
import com.hangzhou.xyj.manager.ShareManager;
import com.hangzhou.xyj.model.DramaModel;
import com.hangzhou.xyj.model.SimpleUserModel;
import com.hangzhou.xyj.model.UserModel;
import com.hangzhou.xyj.model.XXLocation;
import com.hangzhou.xyj.net.handler.GetTokenHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.listener.HttpResponseListener;
import com.hangzhou.xyj.net.request.GetTokenReq;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.mediaideas.videoengine.recorder.AudioRecorder;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.utils.L;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;


public class XYJApplication extends MultiDexApplication {
    private static final String TAG = "XYJApplication";
    public static Context mAppContext = null;
    public static String mToken;//token值
    public static Set<Integer> mFollowIdSet = new HashSet<>();//新增的关注人的列表
    private static XYJApplication instance;
    private static UserModel mUserInfo;//个人信息
    private static String mCity;
    private XXLocation mLocation;
    private AudioRecorder mAudioRecorder;
    private DramaModel mCurrentPlayDramaModel; //当前正在播放的戏曲model

    public static XYJApplication getInstance() {
        return instance;
    }

    public static XYJApplication getApplication(@NonNull Context context) {
        if (context instanceof XYJApplication) {
            return (XYJApplication) context;
        }
        return (XYJApplication) context.getApplicationContext();
    }

    public static UserModel getUserInfo() {
//        if (mUserInfo != null) {
//            //TODO 测试用
//            mUserInfo.setHeadPic("http://dynamic-image.yesky.com/300x-/uploadImages/upload/20140912/upload/201409/oentodzjsz0jpg.jpg");
//        }
        return mUserInfo;
    }

    public void setUserInfo(UserModel userInfo) {
        mUserInfo = userInfo;
    }

    /**
     * 定位失败，取用户信息里面的城市信息
     *
     * @return
     */
    public static String getCity() {
        return mCity;
    }

    /**
     * 获取图片显示option
     *
     * @return
     */
    public static DisplayImageOptions getDisplayOption() {
        // 使用DisplayImageOptions.Builder()创建DisplayImageOptions
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.image_default) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.image_default) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.image_default) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565)
                .resetViewBeforeLoading(false) // 在下载前图片不重置
                .displayer(new FadeInBitmapDisplayer(500))//设置渐变动画
                .build(); // 构建完成
        return options;
    }

    /**
     * 获取token
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/6 14:20
     */
    public static void getToken() {
        GetTokenReq getTokenReq;
        if (XYJApplication.getUserInfo() != null) {
            getTokenReq = new GetTokenReq(getDeviceId(), XYJApplication.getUserInfo().getUserId());
        } else {
            getTokenReq = new GetTokenReq(getDeviceId(), null);
        }

        HttpLoader.getInstance().sendRequest(new GetTokenHandler(getTokenReq, new HttpResponseListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(Object model) {
                mToken = (String) model;
            }

            @Override
            public void onFail(String msg) {

            }

            @Override
            public void onDone(String msg) {

            }

            @Override
            public void onError() {

            }
        }, 0));
    }

    public static String getDeviceId() {
        TelephonyManager tm = (TelephonyManager) mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    public DramaModel getCurrentPlayDramaModel() {
        return mCurrentPlayDramaModel;
    }

    public void setCurrentPlayDramaModel(DramaModel mCurrentPlayDramaModel) {
        this.mCurrentPlayDramaModel = mCurrentPlayDramaModel;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mAppContext = getApplicationContext();

        //初始化用户信息
        initUserInfo();
        if (getCurProcessName(mAppContext).equals("com.hangzhou.xyj")) {//主进程
            Log.d("debug", "主进程初始化");
            //初始化分享管理器
            ShareManager.getInstance().init(mAppContext);
            //初始化ImageLoader
            initImageLoader();
            //初始化聊天信息
            ChatManager.getInstance().init(mAppContext);
            //初始化极光推送
            initJpush();
        }
        reqLocation();//获取定位城市
        Log.d("debug", "=====" + getCurProcessName(mAppContext));
        //初始化crash监控系统
//        CrashReport.initCrashReport(this, AppId.BUGLY, false);
//        //初始化环信easeUI
//        EaseUI.getInstance().init(mAppContext);
        EventBusUtil.register(this);
        getToken();
    }

    String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public AudioRecorder getRecorder() {
        return mAudioRecorder;
    }

    public void setRecorder(@NonNull AudioRecorder recorder) {
        mAudioRecorder = recorder;
    }

    /**
     * 初始化用户信息：通过本地保存的userId配置读取数据库用户信息
     */
    private void initUserInfo() {
        String userId = CommonPreferences.getUserId(this);
        Log.d(TAG, "userId ====" + userId);
        if (StringUtil.isNotBlank(userId)) {
            UserDao userDao = new UserDao(this);
            UserModel userInfo = userDao.getUser(userId);
            setUserInfo(userInfo);
            Log.d(TAG, "userInfo ====" + userInfo == null ? "null" : "not null");
        }
    }

    /**
     * 初始化ImageLoader
     */
    private void initImageLoader() {
        // This configuration tuning is custom. You can tune every option, you may tune some of them,
        // or you can create default configuration by
        //  ImageLoaderConfiguration.createDefault(this);
        // method.
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory());
        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = maxMemory / 8;
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .memoryCacheSizePercentage(30)
                .diskCacheSize(100 * 1024 * 1024)
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .memoryCache(new WeakMemoryCache())
//                .writeDebugLogs() // Remove for release app
                .build();
        // Initialize ImageLoader with configuration.

        ImageLoader.getInstance().init(config);
        L.writeLogs(false);
    }

    /**
     * 初始化极光推送
     */
    private void initJpush() {
        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
    }

    /**
     * 获取当前城市
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/5 16:30
     */
    private void reqLocation() {
        BaiduMapLocationEngine locationEngine = new BaiduMapLocationEngine(this);
        locationEngine.requestLocation();
    }

    /**
     * 获取当前定位地址
     *
     * @return
     */
    public XXLocation getLocation() {
        return mLocation;
    }

    /**
     * 定位消息处理
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/3/30 14:40
     */
    @Subscribe
    public void onEventMainThread(LocationRespEvent event) {
        switch (event.getCode()) {
            case EventCode.SUCCESS:
                mLocation = event.getData();
                if (mLocation != null) {
                    mCity = mLocation.getCity();
                }
                break;
            case EventCode.FAIL:
                mCity = getUserInfo().getZone();
//                //若没有登录
//                if (getUserInfo() == null) {
//                    TipsDialog dialog = new TipsDialog(mAppContext, "提示", "定位失败，是否重试？", "确定", "取消") {
//                        @Override
//                        protected void OnClickNegativeButton() {
//                            this.dismiss();
//                            if (getUserInfo() != null) {
//
//                            }
//                        }
//
//                        @Override
//                        protected boolean OnClickPositiveButton() {
//                            getLocation();
//                            return true;
//                        }
//                    };
//                    dialog.show();
//                }
                break;
        }
    }


    /**
     * 更新环信本地数据库映射
     *
     * @param userModel
     */
    public void updateHXUserDB(UserModel userModel) {
        if (userModel == null) {
            return;
        }
        SimpleUserDao dao = new SimpleUserDao(mAppContext);
        SimpleUserModel hxUser = new SimpleUserModel();
        hxUser.setUserId(userModel.getUserId());
        hxUser.setHeadPic(userModel.getHeadPic());
        hxUser.setNickName(userModel.getNickName());
        dao.addSimpleUser(hxUser);
    }

    /**
     * 应用退出：清空activity和data:应用重置,恢复到未登录状态
     */
    public void exit() {
        //本地配置还是要保存的
//        CommonPreferences.saveUserId(this, "-1");
        setUserInfo(null);
        //清空user数据库
        new UserDao(this).clear();
        //退出环信
        ChatManager.getInstance().logout();
    }

}
